package com.example.bysj_sb.dao;

import com.example.bysj_sb.domain.authority.Permission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@Repository("permissionDao")
public class PermissionDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    //根据id反回Permission对象集合
    public List<Permission> getPermissionsByIds(List<Integer> pIds) {
        List<Permission> permissions = new ArrayList<>();
        for (int i = 0; i < pIds.size(); i++) {
            i = pIds.get(i);
            String sql = "SELECT name, resourceType, url,permission," +
                    "parentId,parentIds,available FROM permission WHERE id = ?";
            permissions = jdbcTemplate.query(sql, new Object[]{i}, new RowMapper() {
                //匿名类
                @Override
                public Object mapRow(ResultSet resultSet, int i) throws SQLException {
                    Permission permission = new Permission();
                    permission.setName(resultSet.getString("name"));
                    permission.setResourceType(resultSet.getString("resourceType"));
                    permission.setUrl(resultSet.getString("url"));
                    permission.setPermission(resultSet.getString("permission"));
                    permission.setParentId(resultSet.getInt("parentId"));
                    permission.setParentIds(resultSet.getInt("parentIds"));
                    permission.setAvailable(resultSet.getInt("available"));
                    return permission;
                }
            });

        }
        return permissions;
    }

    public Boolean add(Permission permission) {
        String sql = "INSERT INTO Permission (name,url,permission) VALUES (?,?,?)";
        int affectedRowNum = jdbcTemplate.update(sql, permission.getName(), permission.getUrl(), permission.getPermission());
        if (affectedRowNum != 1) {
            return false;
        } else {
            return true;
        }
    }
}